package com.ztk.threadbasic.excel.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class CustomCellWidthHanlder implements CellWriteHandler  {

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        int columnIndex = cell.getColumnIndex();

        if (columnIndex != 0) {
            return;
        }

//        //将校验不通过的设置背景色
//        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
//        CellStyle cellStyle = workbook.createCellStyle();
//        // 将原始单元格样式克隆至新建的空的单元格样式对象
//        cellStyle.cloneStyleFrom(cell.getCellStyle());
//        // 设置背景色, 也可以设置其他样式
//        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
//        // cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        // 样式设置到当前单元格
//        //cell.setCellValue("不合格");
//        cell.setCellStyle(cellStyle);

//        XSSFCellStyle cellStyle = (XSSFCellStyle)  writeSheetHolder.getSheet().getWorkbook().createCellStyle();
//        XSSFFont font = (XSSFFont) writeSheetHolder.getSheet().getWorkbook().createFont();
//        font.setBold(true);
//        cellStyle.setFont(font);
//        cell.setCellStyle(cellStyle);
    }

    @Override
    public void afterCellDataConverted(CellWriteHandlerContext context) {
        Cell cell = context.getCell();
        if (context.getHead()) {
            // 处理表头，如果需要的话
            return;
        }

        if (cell.getCellType() != CellType.NUMERIC) {
            return;
        }

        int columnIndex = cell.getColumnIndex();
        if (columnIndex < 2) {
            return;
        }

        int rowIndex = cell.getRowIndex();
        if (rowIndex < 22) {
            return;
        }

        double numericCellValue = cell.getNumericCellValue();
        if ("0.0".equals(String.valueOf(numericCellValue))) {
            return;
        }

        cell.setCellValue(numericCellValue * 100);
        CellStyle cellStyle = cell.getSheet().getWorkbook().createCellStyle();
        cellStyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.00%"));
        cell.setCellStyle(cellStyle);
        context.getFirstCellData().setWriteCellStyle(null);
    }
}
